<template>
  <div class="table" v-loading="loading">
    <div class="table-tools">
      <slot name="tools"></slot>
    </div>
    <el-table
      :data="tableData"
      border
      stripe
      row-key="id"
      lazy
      :load="load"
      :tree-props="{ children: 'children', hasChildren: 'hasChildren' }"
      v-bind="$attrs"
      v-on="$listeners"
    >
      <el-table-column
        type="selection"
        width="50"
        align="center"
      ></el-table-column>
      <slot></slot>
    </el-table>
  </div>
</template>

<script>
export default {
  name: 'TreeTable',
  props: {
    searchData: {
      type: Object,
      default: () => ({})
    },
    service: {
      type: Function,
      required: true
    }
  },
  data() {
    return {
      tableData: [],
      loading: false
    }
  },
  methods: {
    async search() {
      try {
        this.loading = true
        this.tableData = []
        const { data } = await this.service(this.searchData)
        this.tableData = data
      } catch {
        this.tableData = []
      } finally {
        this.loading = false
      }
    },
    async load(tree, treeNode, resolve) {
      const { data } = await this.service({ pid: tree.id })
      resolve(data)
    }
  }
}
</script>

<style lang="scss" scoped>
@import 'styles/common.scss';
.table {
  background-color: $colorWhite;
  border-radius: $borderRadius;
  .table-tools {
    padding: $barPadding;
  }
}
</style>
